const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const { promisify } = require('util');

// readFile 回调方式
function getSalt(cb) {
    fs.readFile(path.resolve(__dirname, '.keys'), 'utf-8', (err, data) => {
        if (err) {
            throw new Error('文件读取失败');
        } else {
            let arr = data.split('\n');
            cb(arr[Math.floor(Math.random() * arr.length)]);
        }
    })
}
// 2. 使用promisify 封装一下
const promisify_getSalt = promisify(getSalt);
// 3. 
(async function getSaltAsync() {
    try {
        let salt = await promisify_getSalt();
        cryptoPwd('123456', salt);
    } catch (e) {
        console.log(e);
    }
})();
function cryptoPwd (pass, salt) {
    let saltpass = pass + ":" + salt;
    console.log('原始密码: %s', pass);
    console.log('加盐后的密码：%s', saltpass);
    const md5 = crypto.createHash('md5');
    let res = md5.update(saltpass).digest('hex');
    console.log('加盐密码的md5值：%s', res);
}
// cryptoPwd('123456', ADMIN_SALT);
// cryptoPwd('654321', ADMIN_SALT);